import {
	ref,
	onUnmounted
} from "vue";

export function useChat(sessionId) {
	const ws = ref(null);
	const messages = ref([]);
	const isConnected = ref(false);

	function connect() {
		const wsUrl = `ws://api.flirtyzsex.com/api/ws/chat/${sessionId}`;
		ws.value = new WebSocket(wsUrl);

		ws.value.onopen = () => {
			console.log("✅ WebSocket 已连接:", sessionId);
			isConnected.value = true;
		};

		ws.value.onmessage = (event) => {
			const data = JSON.parse(event.data);
			messages.value.push({
				sender: data.sender,
				content: data.message,
			});
		};

		ws.value.onclose = () => {
			console.log("❌ WebSocket 已断开");
			isConnected.value = false;
		};
	}

	function sendMessage(msg) {
		if (!msg.trim() || !isConnected.value) return;
		messages.value.push({
			sender: "游客",
			content: msg
		});
		ws.value.send(JSON.stringify({
			message: msg
		}));
	}

	onUnmounted(() => {
		if (ws.value) ws.value.close();
	});

	return {
		messages,
		isConnected,
		connect,
		sendMessage
	};
}